# -*- coding: utf-8 -*-
import json
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from home.model.user_info import User_Info_Serializer
from home.services.user_info_service import User_Info_Service
from home.utils.array_utils import ListTools
from home.utils.post_parameter_getter import ParamGetter
from home.utils.string_utils import StringUtils

@csrf_exempt
def login(request):
	"""
	用户登录服务
	:param request:
	:return:
	"""
	if request.method == "POST":
		login_name = ParamGetter.getParam(request, "login_name")
		login_pwd = ParamGetter.getParam(request, "login_pwd")
		
		if StringUtils.isEmpty(login_name):
			result = {"status": "error", "message": "登录名不允许为空！", "login_status": 0}
		if StringUtils.isEmpty(login_pwd):
			result = {"status": "error", "message": "登录密码不允许为空！", "login_status": 0}
		
		if StringUtils.isNotEmpty(login_name) and StringUtils.isNotEmpty(login_pwd):
			user_Info_Service = User_Info_Service()
			# 根据用户名和密码查询用户是否存在
			users = user_Info_Service.filter_with_condition(email=login_name, user_pwd=login_pwd)
			if ListTools.isNotEmpty(users):
				# 获取用户序列化的JSON字符串
				user_json = json.dumps(User_Info_Serializer.to_json_object(users[0]), ensure_ascii=False)
				# 组织返回结果
				result = {"status": "success", "message": "登录成功！", "login_status": 1, "login_user":user_json}
				# 将用户信息放入Session
				request.session["login_user"] = user_json
				request.session["login_user_name"] = users[0].name
			else:
				result = {"status": "error", "message": "登录名或者登录错误！", "login_status": 0}
		return HttpResponse(json.dumps(result), content_type="application/json")

def logout(request):
	"""
	用户登出服务
	:param request:
	:return:
	"""
	del request.session["login_user"]
	result = {"status": "success", "message": "已成功退出系统", "login_status": 0}
	return HttpResponse(json.dumps(result), content_type="application/json")

def login_user(request):
	"""
	用户登录服务
	:param request:
	:return:
	"""
	if request.method == "GET":
		if "login_user" not in request.session.keys() or request.session["login_user"] is None:
			result = {"status": "error", "message": "未登录", "login_status": 0}
		else:
			result = {"status": "success", "message": "已登录", "login_status": 1,
			          "login_user": request.session["login_user"]}
		return HttpResponse(json.dumps(result), content_type="application/json")
	
	
		
		
